package com.samnative.pineapple.fragment;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.samnative.pineapple.adapter.HomeHotmovieAdapter;
import com.samnative.pineapple.adapter.HomeListAdapter;
import com.samnative.pineapple.adapter.HomeYousuanSubAdapter;
import com.samnative.pineapple.adapter.HomeYugaoAdapter;
import com.samnative.pineapple.entity.BannerModel;
import com.samnative.pineapple.entity.HomeHotmovieModel;
import com.samnative.pineapple.entity.HomeListModel;
import com.samnative.pineapple.entity.HomeYouxuanModel;
import com.samnative.pineapple.entity.HomeYugaoModel;
import com.samnative.pineapple.http.HttpRequest;
import com.samnative.pineapple.http.JsonResult;
import com.samnative.pineapple.instance.AppPrefer;
import com.samnative.pineapple.main.MovieDetailActivity;
import com.samnative.pineapple.main.R;
import com.samnative.pineapple.main.Webview2Activity;
import com.samnative.pineapple.utils.GlideRequestOptions;
import com.samnative.pineapple.utils.GsonUtils;
import com.google.gson.reflect.TypeToken;
import com.gyf.immersionbar.ImmersionBar;
import com.samnative.pineapple.utils.ViewHelper;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.stx.xhb.xbanner.XBanner;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 首页
 */
public class MainHomeFragment extends BaseFragment implements OnClickListener, XBanner.OnItemClickListener, BaseQuickAdapter.OnItemClickListener {

    /**
     * 轮播
     */
    private XBanner mXBanner;
    /**
     * 列表视图
     */
    private RecyclerView recyclerView;
    private SmartRefreshLayout swipeRefreshLayout;
    private HomeListAdapter homeListAdapter;
    /**
     * 轮播数据
     */
    private List<BannerModel> banners;
    /**
     * 热门电影显示
     */
    private RecyclerView rv_hot;
    private HomeHotmovieAdapter hotmovieAdapter;
    /**
     * 热门预告片显示
     */
    private RecyclerView rv_yugao;
    private HomeYugaoAdapter yugaoAdapter;
    /**
     * 列表
     */
    private List<HomeListModel> homeLists;
    /**
     * 状态栏底色
     */
    private View bar_top;
    /**
     * banner的容器
     */
    private RelativeLayout rl_banner_layout;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initView(View view, Bundle bundle) {
        swipeRefreshLayout = find(R.id.swipeRefreshLayout);
        recyclerView = find(R.id.recyclerView);
        bar_top = find(R.id.bar_top);
        banners = new ArrayList<>();
        homeLists = new ArrayList<>();
        homeListAdapter = new HomeListAdapter(homeLists);
        final LinearLayoutManager manager = new LinearLayoutManager(mContext);
        homeListAdapter.addHeaderView(addHeadView());
        recyclerView.setLayoutManager(manager);
        recyclerView.setAdapter(homeListAdapter);
        homeListAdapter.setOnItemClickListener(this);

//        swipeRefreshLayout.autoRefresh();//自动刷新
//        swipeRefreshLayout.autoLoadMore();//自动加载
        swipeRefreshLayout.setEnableLoadMore(false);
        swipeRefreshLayout.setFooterHeight(32);
        swipeRefreshLayout.setEnableFooterTranslationContent(false);
        swipeRefreshLayout.setRefreshHeader(new MaterialHeader(mContext).setShowBezierWave(false));//显示Material系统风格的head
        swipeRefreshLayout.setRefreshFooter(new ClassicsFooter(mContext).setFinishDuration(0).setTextSizeTitle(12));//经典foot ,不显示时间

        swipeRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                requestList(null);
                requestBanner(null);
                requestHot(null);
                requestYugao(null);
            }
        });

        swipeRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
            }
        });


        recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int position = manager.findFirstVisibleItemPosition();
                View firstVisiableChildView = manager.findViewByPosition(position);
                int itemHeight = firstVisiableChildView.getHeight();
                int jl = (position) * itemHeight - firstVisiableChildView.getTop();
                if (jl >= 300) {
                    jl = 300;
                }
                float a = jl / 300f;
                if (Build.VERSION.SDK_INT < 23) {
                    bar_top.setAlpha(a);
                }

                if (jl > 30) {
//                    iv_notice.setImageDrawable(ContextCompat.getDrawable(mContext, R.mipmap.ic_nav_message_black));
//                    iv_icon.setImageDrawable(ContextCompat.getDrawable(mContext, R.mipmap.ic_nav_search_black));
//                    iv_voice.setImageDrawable(ContextCompat.getDrawable(mContext, R.mipmap.ic_nav_voice_black));
//                    et_search.setHintTextColor(ContextCompat.getColor(mContext, R.color.main_tab_text_n2));
                    ImmersionBar.with(getActivity()).statusBarDarkFont(true).init();
                } else {
//                    iv_notice.setImageDrawable(ContextCompat.getDrawable(mContext, R.mipmap.ic_nav_message_white));
//                    iv_icon.setImageDrawable(ContextCompat.getDrawable(mContext, R.mipmap.ic_nav_search_white));
//                    iv_voice.setImageDrawable(ContextCompat.getDrawable(mContext, R.mipmap.ic_nav_voice_white));
//                    et_search.setHintTextColor(ContextCompat.getColor(mContext, R.color.main_white));
                    ImmersionBar.with(getActivity()).statusBarDarkFont(true).init();
                }
            }

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
//                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
//                    int lastVisiblePosition = manager.findLastVisibleItemPosition();
//                    if (lastVisiblePosition >= manager.getItemCount() - 1) {
//                        if (swipeRefreshLayout.isRefreshing()) {//是否正在刷新
//                            return;
//                        }
//                    }
//                }
            }
        });

        requestBanner("");
        requestHot("");
        requestYugao("");
        requestList("");
    }

    /**
     * 返回当前title栏透明度
     *
     * @return
     */
    public float getTitleAlpha() {
//        if (v_top != null) {
//            return v_top.getAlpha();
//        }
        return 0;
    }


    /**
     * 添加头
     *
     * @return
     */
    public View addHeadView() {
        View head = LayoutInflater.from(mContext).inflate(R.layout.head_home_index, null);
        mXBanner = (XBanner) head.findViewById(R.id.xbanner);
        mXBanner.setOnItemClickListener(this);
        rl_banner_layout = head.findViewById(R.id.rl_banner_layout);
        ViewHelper.setHeight(mContext, rl_banner_layout, 1.04f);

        hotmovieAdapter = new HomeHotmovieAdapter(R.layout.item_home_hotmovie);
        hotmovieAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent = new Intent(mContext, MovieDetailActivity.class);
                intent.putExtra("movieid", hotmovieAdapter.getData().get(position).getMovieId());
                startActivity(intent);
            }
        });
        rv_hot = head.findViewById(R.id.rv_hot);
        final LinearLayoutManager manager1 = new LinearLayoutManager(mContext);
        manager1.setOrientation(LinearLayoutManager.HORIZONTAL);
        rv_hot.setLayoutManager(manager1);
        rv_hot.setAdapter(hotmovieAdapter);

        yugaoAdapter = new HomeYugaoAdapter(R.layout.item_home_yugao);
        rv_yugao = head.findViewById(R.id.rv_yugao);
        final LinearLayoutManager gridLayoutManager = new LinearLayoutManager(mContext);
        gridLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rv_yugao.setLayoutManager(gridLayoutManager);
        rv_yugao.setAdapter(yugaoAdapter);

        return head;
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 獲取banner
     *
     * @param loginstr
     */
    public void requestBanner(String loginstr) {
        Map<String, String> map = new HashMap<>();
        map.put("mtoken", AppPrefer.getInstance(mContext).getString(AppPrefer.mtoken, ""));
        HttpRequest.request(getActivity(), "/client/banners/list", loginstr, map, "GET", new JsonResult() {
            @Override
            public void reqestSuccess(JSONObject result) {
                try {
                    JSONArray banner = result.getJSONArray("list");
                    banners = GsonUtils.fromJsonList(banner.toString(), new TypeToken<List<BannerModel>>() {
                    }.getType());
                    mXBanner.setBannerData(banners);
                    mXBanner.loadImage(new XBanner.XBannerAdapter() {
                        @Override
                        public void loadBanner(XBanner banner, Object model, View view, int position) {
                            Glide.with(mContext)
                                    .load(((BannerModel)
                                            model).getXBannerUrl()) //图片地址
                                    .apply(GlideRequestOptions.OPTIONS_600_300)
                                    .into((ImageView) view);
                        }
                    });
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 獲取熱門數據
     *
     * @param loginstr
     */
    public void requestHot(String loginstr) {
        Map<String, String> map = new HashMap<>();
        map.put("mtoken", AppPrefer.getInstance(mContext).getString(AppPrefer.mtoken, ""));
        HttpRequest.request(getActivity(), "/client/movies/hots", loginstr, map, "GET", new JsonResult() {
            @Override
            public void reqestSuccess(JSONObject result) {
                try {
                    JSONArray hots = result.getJSONArray("hots");
                    List<HomeHotmovieModel> list = GsonUtils.fromJsonList(hots.toString(), new TypeToken<List<HomeHotmovieModel>>() {
                    }.getType());
                    hotmovieAdapter.getData().clear();
                    hotmovieAdapter.addData(list);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        });
    }

    /**
     * 獲取热门預告片
     *
     * @param loginstr
     */
    public void requestYugao(String loginstr) {
        Map<String, String> map = new HashMap<>();
        map.put("mtoken", AppPrefer.getInstance(mContext).getString(AppPrefer.mtoken, ""));
        HttpRequest.request(getActivity(), "/client/trailers/list", loginstr, map, "GET", new JsonResult() {
            @Override
            public void reqestSuccess(JSONObject result) {
                try {
                    JSONArray hots = result.getJSONArray("list");
                    List<HomeYugaoModel> list = GsonUtils.fromJsonList(hots.toString(), new TypeToken<List<HomeYugaoModel>>() {
                    }.getType());
                    yugaoAdapter.getData().clear();
                    yugaoAdapter.addData(list);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        });
    }


    /**
     * 獲取猜你喜歡
     *
     * @param loginstr
     */
    public void requestList(String loginstr) {
        Map<String, String> map = new HashMap<>();
        map.put("mtoken", AppPrefer.getInstance(mContext).getString(AppPrefer.mtoken, ""));
        HttpRequest.request(getActivity(), "/client/movies/list", loginstr, map, "GET", new JsonResult() {
            @Override
            public void reqestSuccess(JSONObject result) {
                try {
                    JSONArray banner = result.getJSONArray("list");
                    List<HomeListModel> list = GsonUtils.fromJsonList(banner.toString(), new TypeToken<List<HomeListModel>>() {
                    }.getType());

                    homeLists.clear();
                    homeLists.addAll(list);
                    homeListAdapter.notifyDataSetChanged();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void requestFailure(int code, String msg) {
                super.requestFailure(code, msg);
                swipeRefreshLayout.finishLoadMore();
            }

            @Override
            public void requestFinish() {
                super.requestFinish();
                swipeRefreshLayout.finishRefresh();
            }
        });
    }


    @Override
    public void onItemClick(XBanner banner, Object model, View view, int position) {
        Intent intent = new Intent(mContext, MovieDetailActivity.class);
        intent.putExtra("movieid", banners.get(position).getMovieId());
        startActivity(intent);
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        Intent intent = new Intent(mContext, MovieDetailActivity.class);
        intent.putExtra("movieid", homeListAdapter.getData().get(position).getMovieId());
        startActivity(intent);
    }


    @Override
    public void onStart() {
        super.onStart();
        if (mXBanner != null) {
            mXBanner.startAutoPlay();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        if (mXBanner != null) {
            mXBanner.stopAutoPlay();
        }
    }


    @Override
    public void onResume() {
        super.onResume();
        //注册客服消息监听器
//        JXImManager.Message.getInstance().registerEventListener(messageEventListner);
    }

    @Override
    public void onPause() {
        super.onPause();
        //注销客服消息监听器
//        JXImManager.Message.getInstance().removeEventListener(messageEventListner);
    }


//    private JXEventListner messageEventListner = new JXEventListner() {
//        @Override
//        public void onEvent(final JXEventNotifier eventNotifier) {
//            JXMessage message = (JXMessage) eventNotifier.getData();
//            switch (eventNotifier.getEvent()) {
//                case MESSAGE_NEW:
//                case MESSAGE_OFFLINE:
//                    break;
//                default:
//                    break;
//            }
//        }
//    };

}
